package impl

import "adam2/internal/model"

type Real9QuantAccountDaoImpl struct {
	*BaseDaoImpl
}

// 返回dao实现类
func GetReal9QuantAccountDaoImpl() *Real9QuantAccountDaoImpl {
	return &Real9QuantAccountDaoImpl{GetBaseDaoImpl()}
}

// 返回表名
func (r *Real9QuantAccountDaoImpl) FindTableName() string {
	return "REAL9_Q_ACCOUNT"
}

func (r *Real9QuantAccountDaoImpl) FindAll() model.Real9QuantAccountArray {
	var real9QuantAccountArray model.Real9QuantAccountArray
	r.db.Table("real9_q_account").Select("*").Order("id_ asc").Find(&real9QuantAccountArray)
	return real9QuantAccountArray
}

// 更新real9_q_account表的hold_stock_number、stock_assets、total_assets字段
func (r *Real9QuantAccountDaoImpl) UpdateBeforeSell(holdStockNumber int, stockAssets float64, accountName string) {
	r.db.Exec("update real9_q_account t "+
		"set t.hold_stock_number=?, t.stock_assets = ?, t.total_assets = round(t.capital_assets + ?, 4) where t.account_name = ?",
		holdStockNumber, stockAssets, stockAssets, accountName)
}

// 更新real9_q_account表的hold_stock_number、stock_assets、capital_assets、total_assets、total_stamp_duty、total_registrate_fee_when_sell、total_commission_when_sell字段
func (r *Real9QuantAccountDaoImpl) UpdateAfterSell(sellOrBuyStockNumber int, stockAssets float64, real9QuantAccount model.Real9QuantAccount) {
	r.db.Exec("update real9_q_account t "+
		"set t.hold_stock_number = ?, t.stock_assets = ?, t.capital_assets = round(t.total_assets - ?, 4), "+
		"t.total_stamp_duty = (select COALESCE(sum(t1.stamp_duty), 0) from real9_q_stock_transact_record t1 where t1.account_name = ?), "+
		"t.total_registrate_fee_when_sell = (select COALESCE(sum(t1.registration_fee_when_sell), 0) from real9_q_stock_transact_record t1 where t1.account_name = ?), "+
		"t.total_commission_when_sell = (select COALESCE(sum(t1.commission_when_sell), 0) from real9_q_stock_transact_record t1 where t1.account_name = ?) "+
		"where t.account_name = ?", sellOrBuyStockNumber, stockAssets, stockAssets,
		real9QuantAccount.AccountName, real9QuantAccount.AccountName, real9QuantAccount.AccountName, real9QuantAccount.AccountName)
}

// 清空表
func (r *Real9QuantAccountDaoImpl) TruncateTable() {
	r.db.Exec("truncate table real9_q_account")
}

// 根据日期，从real9_q_account_log表中向real9_q_account表中插入记录
func (r *Real9QuantAccountDaoImpl) InsertFromReal9QuantAccountLogByDate(date string) {
	r.db.Exec("insert into real9_q_account(account_name, hold_stock_number, stock_assets, capital_assets, total_assets, total_stamp_duty, total_registrate_fee_when_buy, total_commission_when_buy, total_registrate_fee_when_sell, total_commission_when_sell) "+
		"select account_name, hold_stock_number, stock_assets, capital_assets, total_assets, total_stamp_duty, total_registrate_fee_when_buy, total_commission_when_buy, total_registrate_fee_when_sell, total_commission_when_sell "+
		"from real9_q_account_log where date_=to_date(?,'yyyy-mm-dd')", date)
}
